package v1

import (
	jwt "github.com/appleboy/gin-jwt/v2"
	"log"
	v4 "mindonmap/api/v4"
	"mindonmap/pkgs/e"
	"mindonmap/pkgs/setting"
	"mindonmap/pkgs/util"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/segmentio/ksuid"
	"mindonmap/models"
	"mindonmap/validation"
)

type Mindmap struct {
	ID         int    `json:"-"`
	Mindid     string `json:"mindid"`
	Acid       int    `json:"acid"`
	Filename   string `json:"filename"`
	Mapdata    string `json:"mapdata"`
	Image      string `json:"image"`
	State      int    `json:"state"`
	Sharestate int    `json:"sharestate"`
	Orders     int    `json:"orders"`
}

type MindRestore struct {
	Mindid string `json:"mindid"`
	T      string `json:"t"`
}

// 获取单个脑图
func GetMindMap(c *gin.Context) {
	var json Mindmap
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}

	valid := validation.Validation{}
	valid.Required(json.Mindid, "mindid").Message("不能为空")

	code := e.INVALID_PARAMS
	var data interface{}
	if !valid.HasErrors() {
		if models.ExistMindMapByIDs(json.Mindid) {
			data = models.GetMindMap(json.Mindid)
			code = e.SUCCESS
		} else {
			code = e.ERROR_NOT_EXIST_ARTICLE
		}
	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

// 获取多个已删除脑图
func GetMindMapsDel(c *gin.Context) {
	data := make(map[string]interface{})
	var mapsdata int
	var maps Mindmap
	valid := validation.Validation{}

	if err := c.BindJSON(&maps); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}

	Userid, err := v4.GetUserID(c)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT),
			"data": make(map[string]interface{}),
		})
		return
	}

	code := e.INVALID_PARAMS
	if !valid.HasErrors() {
		code = e.SUCCESS
		data["lists"] = models.GetDelMindMaps(util.GetPage(c), setting.PageSize, Userid)
		data["total"] = models.GetMindMapDelTotal(mapsdata)

	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

// 获取多个脑图
func GetMindMaps(c *gin.Context) {
	data := make(map[string]interface{})
	mapsdata := make(map[string]interface{})
	var maps Mindmap
	valid := validation.Validation{}

	if err := c.BindJSON(&maps); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	Userid, err := v4.GetUserID(c)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT),
			"data": make(map[string]interface{}),
		})
		return
	}

	if maps.State == 3 {
		mapsdata["state"] = maps.State
	} else {
		mapsdata["state"] = maps.State
		mapsdata["acid"] = Userid
	}

	var sorts string
	switch maps.Orders {
	case 1:
		sorts = "createtime desc"
	case 2:
		sorts = "createtime desc"
	case 3:
		sorts = "createtime desc"
	case 4:
		sorts = "createtime desc"
	default:
		sorts = "createtime desc"
	}

	code := e.INVALID_PARAMS
	if !valid.HasErrors() {
		code = e.SUCCESS
		if maps.State == 3 {
			data["lists"] = models.GetMindMapsTempate(util.GetPage(c), setting.PageSize, mapsdata)
		} else {
			data["lists"] = models.GetMindMapslist(util.GetPage(c), setting.PageSize, Userid, sorts)
		}
		data["total"] = models.GetMindMapTotal(Userid)

	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

// 新增脑图
func AddMindMap(c *gin.Context) {
	var json Mindmap

	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	Userid, err := v4.GetUserID(c)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT),
			"data": make(map[string]interface{}),
		})
		return
	}
	var total = v4.MindMapTotal(Userid)
	pc := v4.NewPrivilegeController()
	var isvip = v4.IsVip(c)
	var CheckPriv bool
	if isvip {
		CheckPriv = pc.CheckPrivilege("vip", "cloud_storage_limit", total)
	} else {
		CheckPriv = pc.CheckPrivilege("free", "cloud_storage_limit", total)
	}
	if !CheckPriv {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_PERMISSION,
			"msg":  e.GetMsg(e.ERROR_AUTH_PERMISSION),
			"data": make(map[string]interface{}),
		})
		return
	}
	Mindid := ksuid.New().String()
	code := e.INVALID_PARAMS
	data := make(map[string]interface{})
	if !models.ExistMindMapByMindID(Mindid) {

		image := util.WriteFile(strconv.Itoa(Userid), json.Mindid, json.Image)
		if len(image) > 0 {
			var aws3 = setting.GetAWSS3()
			S3Host := aws3.S3Host
			image = S3Host + image
		}

		data["mindid"] = Mindid
		data["acid"] = Userid
		data["filename"] = json.Filename
		data["mapdata"] = json.Mapdata
		data["image"] = image
		data["state"] = 0
		models.AddMindMap(data)
		//data["id"]=models.GetMindMapID(Mindid)
		code = e.SUCCESS
	} else {
		data["mindid"] = Mindid
		data["acid"] = Userid
		data["filename"] = json.Filename
		data["mapdata"] = json.Mapdata
		//data["id"]=models.GetMindMapID(json.Mindid)
		code = e.ERROR_EXIST_PARAMS
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

// 保存脑图
func EditMindMap(c *gin.Context) {
	var json Mindmap
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	Userid, err := v4.GetUserID(c)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT),
			"data": make(map[string]interface{}),
		})
		return
	}

	code := e.INVALID_PARAMS
	if models.ExistMindMapByIDs(json.Mindid) {
		image := util.WriteFile(strconv.Itoa(Userid), json.Mindid, json.Image)
		if len(image) > 0 {
			var aws3 = setting.GetAWSS3()
			S3Host := aws3.S3Host
			image = S3Host + image
		}
		data := make(map[string]interface{})
		data["mapdata"] = json.Mapdata
		data["modifietime"] = time.Now().Unix()
		data["image"] = image
		claims := jwt.ExtractClaims(c)
		util.WriteLog("UserJWT：" + claims["username"].(string) + "|" + claims["userId"].(string) + ":")
		models.EditMindMap(json.Mindid, data)
		code = e.SUCCESS
		datas := make(map[string]interface{})

		// 离开时则更新版本1
		if json.State == 0 {
			if !models.ExistMindVersionBySourceID(json.Mindid) {
				datas["pid"] = json.Mindid
				datas["acid"] = Userid
				datas["mapdata"] = json.Mapdata
				datas["state"] = 0
				datas["image"] = image
				datas["version"] = 1
				models.AddMindVersion(datas)
			} else {
				datas["pid"] = json.Mindid
				datas["acid"] = Userid
				datas["mapdata"] = json.Mapdata
				datas["image"] = image
				datas["modifietime"] = time.Now().Unix()
				datas["version"] = 1
				models.EditMindVersionSource(json.Mindid, datas)
			}
		}
	} else {
		code = e.ERROR_NOT_EXIST_ARTICLE
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": make(map[string]string),
	})
}

// 批量删除脑图
func DeleteMindMaps(c *gin.Context) {
	type mindmaplist struct {
		Mindid []string
	}
	var json mindmaplist
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	valid := validation.Validation{}
	valid.Required(json.Mindid, "mindid").Message("不能为空")
	Userid, err := v4.GetUserID(c)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}

	code := e.INVALID_PARAMS
	if !valid.HasErrors() {
		data := make(map[string]interface{})
		data["state"] = 1
		data["statetime"] = time.Now().Unix()
		models.DeleteMindMaps(json.Mindid, Userid, data)
		code = e.SUCCESS
	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": make(map[string]string),
	})
}

// 删除脑图
func DeleteMindMap(c *gin.Context) {
	var json Mindmap
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}

	valid := validation.Validation{}
	valid.Required(json.Mindid, "mindid").Message("不能为空")

	code := e.INVALID_PARAMS
	if !valid.HasErrors() {
		if models.ExistMindMapByIDs(json.Mindid) {
			data := make(map[string]interface{})
			data["state"] = 1
			data["statetime"] = time.Now().Unix()
			models.DeleteMindMap(json.Mindid, data)
			code = e.SUCCESS
		} else {
			code = e.ERROR_NOT_EXIST_ARTICLE
		}
	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": make(map[string]string),
	})
}

// 回收站还原
func RestoreMindMap(c *gin.Context) {
	var json MindRestore
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}

	valid := validation.Validation{}
	valid.Required(json.Mindid, "mindid").Message("不能为空")
	valid.Required(json.T, "t").Message("不能为空")

	code := e.INVALID_PARAMS
	if !valid.HasErrors() {
		if models.ExistMindMapAndFlowByID(json.Mindid, json.T) {
			data := make(map[string]interface{})
			data["state"] = 0
			data["statetime"] = time.Now().Unix()
			if json.T == "m" {
				models.DeleteMindMap(json.Mindid, data)
			}
			if json.T == "f" {
				models.DeleteMindFlow(json.Mindid, data)
			}
			code = e.SUCCESS
		} else {
			code = e.ERROR_NOT_EXIST_ARTICLE
		}
	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": make(map[string]string),
	})
}

// 彻底移除回收站
func DelMindMap(c *gin.Context) {
	var json Mindmap
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}

	valid := validation.Validation{}
	valid.Required(json.Mindid, "mindid").Message("不能为空")

	code := e.INVALID_PARAMS
	if !valid.HasErrors() {
		if models.ExistMindMapByIDs(json.Mindid) {
			data := make(map[string]interface{})
			data["state"] = 2
			data["statetime"] = time.Now().Unix()
			models.DeleteMindMap(json.Mindid, data)
			code = e.SUCCESS
		} else {
			code = e.ERROR_NOT_EXIST_ARTICLE
		}
	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": make(map[string]string),
	})
}

// 清空回收站
func CleanRecycleMindMap(c *gin.Context) {

	valid := validation.Validation{}
	Userid, err := v4.GetUserID(c)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}

	code := e.INVALID_PARAMS
	if !valid.HasErrors() {
		data := make(map[string]interface{})
		data["state"] = 2
		data["statetime"] = time.Now().Unix()
		models.DeleteAllMindMaps(Userid, data)
		code = e.SUCCESS
	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": make(map[string]string),
	})
}

// 脑图重命名
func RenameMind(c *gin.Context) {
	var json Mindmap
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	code := e.INVALID_PARAMS
	if models.ExistMindMapByIDs(json.Mindid) {
		data := make(map[string]interface{})
		data["filename"] = json.Filename
		models.EditMindMap(json.Mindid, data)
		code = e.SUCCESS
	} else {
		code = e.ERROR_NOT_EXIST_ARTICLE
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": make(map[string]string),
	})
}
